/*
 * AuthenticationFilter.java
 * 作用：认证过滤器，确保用户在访问受保护的页面（如`/user/*`、`/admin/*`）前必须登录。
 */
package com.campustradingwall.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import com.campustradingwall.dao.MessageDao;
import com.campustradingwall.model.User;

// 拦截所有对/user/和/admin/路径以及特定操作的请求
@WebFilter(urlPatterns = {"/user/*", "/admin/*", "/buy", "/addProduct", "/user/messages"})
public class AuthenticationFilter implements Filter {

    private MessageDao messageDao;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter初始化代码
        messageDao = new MessageDao();
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        boolean loggedIn = (session != null && session.getAttribute("user") != null);

        if (loggedIn) {
            // 用户已登录，继续处理请求
            User currentUser = (User) session.getAttribute("user");
            if (currentUser != null) {
                int unreadMessageCount = messageDao.getUnreadMessageCount(currentUser.getId());
                session.setAttribute("unreadMessageCount", unreadMessageCount);
            }
            chain.doFilter(request, response);
        } else {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }

    @Override
    public void destroy() {
        // Filter销毁代码
    }
} 